# 题目描述
给定一个 N 叉树,返回其节点值的后序遍历。
例如,给定一个 3叉树
:
返回其后序遍历: [5,6,3,2,4,1].
说明: 递归法很简单,你可以使用迭代法完成此题吗?
来源:LeetCode
# 思路
用一个栈依次压入节点和子节点,若无子节点则弹出计入结果。 注意两点:
- 压入子节点的时候需要从后往前压入,这样保证前面子节点能够先被遍历。
- 子节点压入完成后,将子节点置空,不然下次遍历到还会认为是有子节点的。
# 解法
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node} root
* @return {number[]}
*/
const postorder = root => {
const stack = [];
const result = [];
if (!root) return result;
stack.push(root);
let node;
while (stack.length) {
node = stack[stack.length - 1];
if (node.children) {
stack.push(...node.children.reverse());
node.children = null;
} else {
result.push(node.val);
stack.pop();
}
}
return result;
};